<?php

class Controllers_Login extends RestController {
	public function get() {
            $this->response = array('TestResponse' => null);
            $this->responseStatus = 501;
	}
        
	public function post() {
                require_once("Config/connexion.php");
                
                $params = $this->request['params'];
                
                $responseStatus = 200;
                
                $user = R::findOne('tg_users',' username = :username and password = :password', array(':username'=>$params["username"], ':password'=>$params["password"] ));
              
                if ($user != null) {
                    
                    $user->keyauth = $this->getRandomString();
                    R::store($user);
                    
                    $this->response = array('Response' => array('id' => $user->id, 'key' => $user->keyauth));
                }
                else {
                    $this->response = array('Response' => "Login failed");
                    $responseStatus = 403;
                }
                
                $this->responseStatus = $responseStatus;
	}
	public function put() {
		$this->response = array('TestResponse' => null);
		$this->responseStatus = 501;
	}
        
	public function delete() {
		$this->response = array('TestResponse' => null);
		$this->responseStatus = 501;
	}
        
        private function getRandomString($length = 32) {
            $validCharacters = "abcdefghijklmnopqrstuxyvwzABCDEFGHIJKLMNOPQRSTUXYVWZ";
            $validCharNumber = strlen($validCharacters);

            $result = "";

            for ($i = 0; $i < $length; $i++) {
                $index = mt_rand(0, $validCharNumber - 1);
                $result .= $validCharacters[$index];
            }

            return $result;
        }
}